﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using Dict.Blo;
using Dict.DataModel;

namespace UI
{
    [RequireComponent(typeof(UILuckEvent))]
    public class UILuck : Page
    {
        public UILuckCirclePanel panel;

        #region 四个上阵位置
        public Transform inBattlePosOne;
        public Transform inBattlePosTwo;
        public Transform inBattlePosThree;
        public Transform inBattlePosFour;
        #endregion
        #region 四个Mask
        public GameObject mask0, mask1, mask2, mask3;
        #endregion

        #region 左边三个助阵位子
        public Transform helpBattlePosLeftOne;
        public Transform helpBattlePosLeftTwo;
        public Transform helpBattlePosLeftThree;
        #endregion

        #region 右边三个助阵位置
        public Transform helpBattlePosRightOne;
        public Transform helpBattlePosRightTwo;
        public Transform helpBattlePosRightThree;
        #endregion

        #region lock logic
        public GameObject[] sixLocks;
        public GameObject[] sixAdds;
        public GameObject[] fourLocks;
        public GameObject[] fourAdds;
        #endregion

        #region HeroIcon
        public GameObject heroIcon;
        #endregion

        #region Label
        public UILabel leftOne;
        public UILabel leftTwo;
        public UILabel leftThree;
        public UILabel rightOne;
        public UILabel rightTwo;
        public UILabel rightThree;

        public UILabel luckTotalCount;
        public UILabel luckHeroName;
        public UILabel luckCount;
        #endregion

        #region 模版
        public GameObject prefab;
        #endregion
        public UIGrid prefabGrid;

        #region 缓存
        List<GameObject> cached = new List<GameObject>();
        List<GameObject> itemcached = new List<GameObject>();
        #endregion

       
        Transform[] battlePos;
        Transform[] helpPos;
        UILabel[] helpNamePos;
        


        #region cached string
        string guid;
        string hasStr;
        #endregion

        int currIndex = 0;


        public GameObject popupBox;

        void Awake()
        {
            OnceInit();
        }

        public void ShowPopupBox(string luckId)
        {
            popupBox.SetActive(true);
            var script = popupBox.GetComponent<UILuckPopupBox>();

            bool actived = false;
            bool find = false;
            foreach(var hero in StaticData.playerData.InstPlayerData.BattleCamps)
            {
                if (find) break;
                foreach(var luck in hero.Value.lucks)
                {
                    if(luck.luckData.id == luckId)
                    {
                        actived = luck.IsActived;
                        find = true;
                        break;
                    }
                }
            }

            script.Init(luckId, actived);
        }
    
        private void OnceInit()
        {
            battlePos = new Transform[4]
            {
                inBattlePosOne ,
                inBattlePosTwo,
                inBattlePosThree,
                inBattlePosFour
            };

            helpPos = new Transform[6]
            {
                helpBattlePosLeftOne,
                helpBattlePosLeftTwo,
                helpBattlePosLeftThree,
                helpBattlePosRightOne,
                helpBattlePosRightTwo,
                helpBattlePosRightThree
            };

            helpNamePos = new UILabel[6]
            {
                leftOne,
                leftTwo,
                leftThree,
                rightOne,
                rightTwo,
                rightThree
            };

            currIndex = 1;
        }

        protected override void DoOpen()
        {
            Init(true); 
        }

        protected override void DoClose()
        {
            Uninit();
        }

        public override void OnCoverPageRemove()
        {
            Init(false);
        }


        private void LocksLogic()
        {
            fourAdds[0].SetActive(CommonMethod.GetModuleOpen("array_pos1"));
            fourAdds[1].SetActive(CommonMethod.GetModuleOpen("array_pos2"));
            fourAdds[2].SetActive(CommonMethod.GetModuleOpen("array_pos3"));
            fourAdds[3].SetActive(CommonMethod.GetModuleOpen("array_pos4"));

            fourLocks[0].SetActive(!CommonMethod.GetModuleOpen("array_pos1"));
            fourLocks[1].SetActive(!CommonMethod.GetModuleOpen("array_pos2"));
            fourLocks[2].SetActive(!CommonMethod.GetModuleOpen("array_pos3"));
            fourLocks[3].SetActive(!CommonMethod.GetModuleOpen("array_pos4"));

            sixAdds[0].SetActive(CommonMethod.GetModuleOpen("array_help_pos1"));
            sixAdds[1].SetActive(CommonMethod.GetModuleOpen("array_help_pos2"));
            sixAdds[2].SetActive(CommonMethod.GetModuleOpen("array_help_pos3"));
            sixAdds[3].SetActive(CommonMethod.GetModuleOpen("array_help_pos4"));
            sixAdds[4].SetActive(CommonMethod.GetModuleOpen("array_help_pos5"));
            sixAdds[5].SetActive(CommonMethod.GetModuleOpen("array_help_pos6"));

            sixLocks[0].SetActive(!CommonMethod.GetModuleOpen("array_help_pos1"));
            sixLocks[1].SetActive(!CommonMethod.GetModuleOpen("array_help_pos2"));
            sixLocks[2].SetActive(!CommonMethod.GetModuleOpen("array_help_pos3"));
            sixLocks[3].SetActive(!CommonMethod.GetModuleOpen("array_help_pos4"));
            sixLocks[4].SetActive(!CommonMethod.GetModuleOpen("array_help_pos5"));
            sixLocks[5].SetActive(!CommonMethod.GetModuleOpen("array_help_pos6"));
        }

        private void Init(bool useParam)
        {
            LocksLogic();
            popupBox.SetActive(false);

            foreach(var obj in cached)
            {
                Destroy(obj);
            }
            cached.Clear();

            foreach (var it in StaticData.playerData.InstPlayerData.BattleCamps)
            {
                var index = it.Key - 1;
                var hero = it.Value.hero;
                if (hero != null)
                {
                    SetInBattleHeroIcon(hero.heroId, hero.level, battlePos[index]);
                }
            }

            var hasParam = options.ContainsKey("pos");
            if (useParam && hasParam)
            {
                currIndex = int.Parse(options["pos"].Trim());
            }

            var firstHero = StaticData.playerData.InstPlayerData.BattleCamps[currIndex];
            SetCenterHero(firstHero);
            

            int i = 1;
            foreach(var it in helpNamePos)
            {
                if(CommonMethod.GetModuleOpen("array_help_pos" +i))
                {
                    SetHeroNameLabel(it, TableTextBlo.GetText("help_battle"));
                }
                else
                {
                    var str0 = TableTextBlo.GetText("x_level_open");
                    var str1 = "" + string.Format(str0, Dict.DictModuleBlo.GetTableModule("array_help_pos" + i).openLev);
                    SetHeroNameLabel(it, str1);
                }
                i++;
            }

            foreach (var it in StaticData.playerData.InstPlayerData.GetHelpCamps())
            {
                var index = it.Key - 1;
                var hero = StaticData.playerData.GetUIHero( it.Value.guid );
                if (hero != null)
                {
                    SetHelpHeroIcon(hero.heroId,hero.guid, hero.level, helpPos[index],index+1);
                    SetHeroNameLabel(helpNamePos[index], hero.heroName);
                }
            }

            UpdateCirclePanel();
        }

        private void Uninit()
        {
            currIndex = 1;
            foreach(var obj in cached)
            {
                GameObject.Destroy(obj);
            }
            cached.Clear();
            foreach(var obj in itemcached)
            {
                GameObject.Destroy(obj);
            }
            itemcached.Clear();
        }
        protected void SetInBattleHeroIcon(string heroId,int level,Transform tr)
        {
            GameObject obj = Instantiate(heroIcon) as GameObject;
            obj.SetActive(true);
            obj.transform.SetParent(tr);
            obj.transform.localScale = Vector3.one * 0.70f;
            obj.transform.localPosition = Vector3.zero;
            var script = obj.GetComponent<HeroIcon>();
            script.SetHeroWithId(heroId);
            script.SetLevel(level);
            obj.transform.SetParent(tr.parent);
            script.m_callback = delegate 
            {
                foreach(var hero in StaticData.playerData.InstPlayerData.BattleCamps)
                {
                    if (hero.Value.hero != null && hero.Value.hero.heroId == heroId)
                    {
                        SetCenterHero(hero.Value);
                        currIndex = hero.Key;
                        break;
                    }
                }
            };
            cached.Add(obj);
        }
        protected void SetHelpHeroIcon(string heroId,string guid,int level,Transform tr,int pos)
        {
            GameObject obj = Instantiate(heroIcon) as GameObject;
            obj.SetActive(true);
            obj.transform.SetParent(tr);
            obj.transform.localScale = Vector3.one;
            obj.transform.localPosition = Vector3.zero;
            var script = obj.GetComponent<HeroIcon>();
            script.SetHeroWithId(heroId);
            script.SetLevel(level);
            script.m_callback = delegate
            {
                PageManager.Instance.OpenPage("UIHeroPage", "guid=" + guid+"&showUnloadHero=true&showSwitchHero=false");
                var heroPage = PageManager.Instance.currentPage as UIHeroPage;
                var eventPage = heroPage.GetComponent<UIHeroEvent>();
                eventPage.uploadHeroHandler = delegate 
                {
                    var off = new ProtoBuf.Message.CSHelperOff();
                    off.pos = pos;
                    NetAPI.SendHttp(ProtoBuf.Message.OpDefine.CSHelperOff,off, (o, ok) =>
                    {
                        if(ok)
                        {
                            StaticData.playerData.InstPlayerData.RemoveHelpCamp(pos);
                            heroPage.Close();
                        }
                    });
                };

                var heroLogic = heroPage.logic;
                heroLogic.SetHero(true, true, true);
                var heroEvt = heroPage.GetComponent<UIHeroEvent>();
                heroEvt.switchHeroHandler = delegate
                {
                    int n = pos;
                    string str = "array_help_pos" + n;
                    if (CommonMethod.GetModuleOpen(str))
                    {
                        PageManager.Instance.OpenPage("HeroReplacePage", "index=" + n + "&help=true");
                    }
                    else
                    {
                        string str0 = TableTextBlo.GetText("character_level_charge") + Dict.DictModuleBlo.GetTableModule(str).openLev;
                        BoxManager.CreatePopupTextBox(str0);
                    }
                };
            };
            obj.transform.SetParent(tr.parent);

            cached.Add(obj);
        }
        protected void SetHeroNameLabel(UILabel txt, string heroName)
        {
            txt.text = heroName;
        }
        
        protected void SetCenterHero(UIHeroFormation hero)
        {
            this.guid = hero.hero.guid;
            var lucks = DictLuckBlo.GetLucksByHeroId(hero.hero.heroId);
            
            foreach(var item in itemcached)
            {
                GameObject.Destroy(item);
            }
            itemcached.Clear();
            
            StopAllCoroutines();
            StartCoroutine(_CreateLuckItems(lucks,hero));
            
            UpdateCirclePanel();
            MaskOther(hero);
        }

        private void MaskOther(UIHeroFormation hero)
        {
            var ls = StaticData.playerData.InstPlayerData.BattleCamps;

            mask0.SetActive(false);
            mask1.SetActive(false);
            mask2.SetActive(false);
            mask3.SetActive(false);

            if (ls[1].hero != null) mask0.SetActive(true);
            if (ls[2].hero != null) mask1.SetActive(true);
            if (ls[3].hero != null) mask2.SetActive(true);
            if (ls[4].hero != null) mask3.SetActive(true);

            foreach (var it in ls)
            {
                if (it.Value != null && 
                    it.Value.hero != null && 
                    it.Value.hero.guid == hero.hero.guid)
                {
                    if (it.Key == 1) mask0.SetActive(false);
                    if (it.Key == 2) mask1.SetActive(false);
                    if (it.Key == 3) mask2.SetActive(false);
                    if (it.Key == 4) mask3.SetActive(false);

                    break;
                }
            }
        }

        /// <summary>
        /// 这个是Luck的小项
        /// </summary>
        /// <param name="lucks"></param>
        /// <param name="hero"></param>
        /// <returns></returns>
        private IEnumerator _CreateLuckItems(List<TableYuan> lucks,UIHeroFormation hero)
        {
            int i = 0;
            foreach (var luck in lucks)
            {
                bool actived = false;

                foreach (var inner in hero.lucks)
                {
                    if (inner.luckData.id == luck.id)
                    {
                        inner.FreshLuckActived();
                        actived = inner.IsActived;
                        break;
                    }
                }
                if(++i%3==0) yield return null;

                CreateLuckItem(luck.id, actived);
                prefabGrid.Reposition();
            }

            yield return null;
            
        }

        /// <summary>
        /// 缘分Grid
        /// </summary>
        /// <param name="luckId"></param>
        /// <param name="acitved"></param>
        private void CreateLuckItem(string luckId,bool acitved)
        {
            GameObject inst = (GameObject)Instantiate(prefab);
            inst.transform.SetParent(prefabGrid.transform);
            inst.transform.localScale = Vector3.one;
            inst.transform.localPosition = Vector3.zero;
            inst.SetActive(true);
            inst.name = luckId;
            var script = inst.GetComponent<UILuckTextTemplate>();
            var dict = DictLuckBlo.GetLuckByLuckId(luckId);
            script.Init(dict.id, acitved);   
            itemcached.Add(inst);
        }
        
        /// <summary>
        /// 圈形组件
        /// </summary>
        private void UpdateCirclePanel()
        {
            UIHeroFormation hero = null;

            foreach(var h in StaticData.playerData.InstPlayerData.BattleCamps)
            {
                if (h.Value.hero.guid == this.guid)
                {
                    hero = h.Value;break;
                }
            }

            panel.Init(hero.hero.guid);
            UpdateLuckCount();
        }


        private void UpdateLuckCount()
        {
            UIHeroFormation hero = null;
            foreach (var h in StaticData.playerData.InstPlayerData.BattleCamps)
            {
                if (h.Value.hero!=null && 
                    h.Value.hero.guid == this.guid)
                {
                    hero = h.Value;
                }
            }

            luckHeroName.text = CommonMethod.GetHeroName(hero.hero.heroId) +" "+ hero.hero.GetHeroSpaceName();

            //个人缘分
            int count = 0;
            foreach (var luck in hero.lucks)
            {
                if (luck.IsActived) count++;
            }

            luckCount.text = string.Format(TableTextBlo.GetText("luck_count_name"), "[ffde00]"+count+"[-]");

            //总缘分
            count = 0;
            foreach (var it in StaticData.playerData.InstPlayerData.BattleCamps)
            {
                foreach (var luck in it.Value.lucks)
                {
                    if(luck.IsActived) count++;
                }
            }
            luckTotalCount.text = count.ToString();
        }

        #region 静态工具
        static public void ShowLuckPopupBox(string luckId)
        {
            var luck = (UILuck)PageManager.Instance.currentPage;
            luck.ShowPopupBox(luckId);
            
        }

        static public bool LuckActived(string luckId, string heroId)
        {
            bool actived = false;

            return actived;
        }
        #endregion

    }
}
